import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class Client {
	static int wait_t = 5;
	static int retry = 16;
	static long timeout = 2500;
	static String ip = new String();
        public static void enviar(String pacote, String type) {
                try {
                	int i;
                	long j = 0;
                	MainPc.msg_id++;
                	boolean check=false;
                	if ( type == MainPc.type)
                		pacote = type+"@"+MainPc.msg_id+"@"+pacote;
                	System.out.println("pacote: " + pacote);
                    // Retrieve the ServerName
                    InetAddress serverAddr = InetAddress.getByName(ip);
                   
                    //Log.d("UDP", "C: Connecting...");
                    /* Create new UDP-Socket */
                    DatagramSocket socket = new DatagramSocket();
             
                    /* Prepare some data to be sent. */
                    byte[] outData = (pacote).getBytes();
                    /* Create UDP-packet with
                     * data & destination(url+port) */
                    DatagramPacket packet = new DatagramPacket(outData, outData.length,     serverAddr, 1236);
                    //Log.d("UDP", "C: Sending: '" + new String(outData) + "'");
                    /* Send out the packet */
                    //espera ate o Android confirmar que recebeu o pacote
                    if ( type == MainPc.type) {
                        while(!check) {
                        	j++;
	                        socket.send(packet);
	                        System.out.println("pacote: " + pacote);
	             			//se message == pacote entao o android recebeu o pacote e mandou ele de volta pode continuar
	             			for (i=0; i < retry && !check; i++) {
	             				if (Server.ok_message!=null && Server.ok_message.equals(pacote)) {
	             					check=true;
	             					System.out.println("Sucess: Message received! : " + Server.ok_message);
	             				}
	             				else {
	             					Thread.sleep(wait_t);
	             				}
	             			}
	             			if ( j > (timeout/(retry*wait_t)) ) {
	             				check = true;
	             				System.out.println("Error: did not receive answer.");
	             			}
                        }
                    }
                    else {
                    	socket.send(packet);
                    }
              
                    
                    //Log.d("UDP", "C: Sent.");
                    //Log.d("UDP", "C: Done.");
                } catch (Exception e) {
                        //Log.e("UDP", "C: Error", e);
                }
        }
}